package com.yugao.fintech.antelope.base.security.aspect;

import com.yugao.fintech.antelope.base.security.annotation.InnerAuth;
import com.yugao.fintech.antelope.base.security.excetion.AccessDeniedException;
import com.yugao.fintech.antelope.base.security.utils.SecurityUtils;
import com.yugao.fintech.antelope.base.model.module.auth.LoginUser;
import com.yugao.fintech.framework.assistant.utils.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 内部服务调用验证处理
 */
@Slf4j
@Aspect
@Component
public class InnerAuthAspect implements Ordered {
    @Around("@annotation(innerAuth)")
    public Object innerAround(ProceedingJoinPoint point, InnerAuth innerAuth) throws Throwable {
        // 内部请求验证
        if (!SecurityUtils.isFromInner()) {
            log.warn("访问接口 {} 没有权限", point.getSignature().getName());
            throw new AccessDeniedException();
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 用户信息验证
        if (innerAuth.verifyUser() && Objects.isNull(loginUser)) {
            throw new BizException("用户登录信息为空，不允许访问 ");
        }
        return point.proceed();
    }

    /**
     * 确保在权限认证aop执行前执行
     */
    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 100;
    }
}
